#include "titlebar.h"
#include <QStyle>
#include <QMenu>
#include <QAction>
#include <QDebug>

TitleBar::TitleBar(QWidget *parent) : QWidget(parent)
{
	mousePressedFlag = false;

    closeBtn = new QToolButton;
    closeBtn->setIcon(QIcon(":/icons/close.png"));

    addBtn = new QToolButton;
    addBtn->setIcon(QIcon(":/icons/add.png"));
    addBtn->setToolTip(tr("添加新标签"));

    titleLbl = new QLabel;
    titleLbl->setToolTip(tr("点击鼠标右键显示工具栏"));

    mainLyt = new QHBoxLayout;
    mainLyt->setMargin(0);
    mainLyt->setSpacing(0);

    mainLyt->addWidget(addBtn);
    mainLyt->addWidget(titleLbl);
    //mainLyt->addWidget(closeBtn);

    qssFile = new QFile(":/qss/titlebar.qss");
    if (qssFile->open(QFile::ReadOnly)) {
        qssData = QString::fromUtf8(qssFile->readAll());
        this->setStyleSheet(qssData);
    }

    connect(closeBtn, &QToolButton::clicked, this, &TitleBar::on_closeBtn_clicked);
    connect(addBtn, &QToolButton::clicked, this, &TitleBar::on_addBtn_clicked);

	this->setLayout(mainLyt);
    //this->setFixedHeight(80);
    //this->setStyleSheet("background-color:gray");
}

void TitleBar::setTitle(const QString &title)
{
    titleLbl->setText(title);
}

void TitleBar::mousePressEvent(QMouseEvent *event)
{
	if (event->button() == Qt::LeftButton) {
		mousePressedFlag = true;
		curPos = event->pos();
        emit pressed();
    } else if (event->button() == Qt::RightButton) {
        emit expand();
    }
}
void TitleBar::mouseMoveEvent(QMouseEvent *event)
{
	if (!mousePressedFlag) {
		return;
	}
	emit moved(event->globalPos() - curPos + pos());
}
void TitleBar::mouseReleaseEvent(QMouseEvent *event)
{
	mousePressedFlag = false;

    emit released();
    event->accept();

}

void TitleBar::on_closeBtn_clicked()
{
	emit closeWindow();
}

void TitleBar::on_addBtn_clicked()
{
    emit add();
}
